package com.yuanqi.java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.java.dto.PurchaseReturnOrderDTO;
import com.yuanqi.java.dto.PurchaseReturnOrderVO;
import com.yuanqi.java.dto.PurchaseReturnOrderItemVO;
import com.yuanqi.java.dto.PurchaseReturnOrderAuditVO;
import com.yuanqi.java.entity.PurchaseReturnOrder;
import com.yuanqi.java.entity.PurchaseReturnOrderItem;
import com.yuanqi.java.entity.PurchaseReturnOrderAudit;
import com.yuanqi.java.entity.PurchaseOrderItem;
import com.yuanqi.java.mapper.PurchaseReturnOrderMapper;
import com.yuanqi.java.mapper.PurchaseReturnOrderItemMapper;
import com.yuanqi.java.mapper.PurchaseReturnOrderAuditMapper;
import com.yuanqi.java.mapper.PurchaseOrderItemMapper;
import com.yuanqi.java.service.IPurchaseReturnOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 采购退货单Service实现类
 */
@Service
@RequiredArgsConstructor
public class PurchaseReturnOrderServiceImpl implements IPurchaseReturnOrderService {

	private final PurchaseReturnOrderMapper returnOrderMapper;
	private final PurchaseReturnOrderItemMapper returnOrderItemMapper;
	private final PurchaseReturnOrderAuditMapper returnOrderAuditMapper;
	private final PurchaseOrderItemMapper purchaseOrderItemMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long createReturnOrder(PurchaseReturnOrderDTO dto) {
		// 创建退货单主表
		PurchaseReturnOrder returnOrder = new PurchaseReturnOrder();
		returnOrder.setReturnNo(generateReturnNo());
		returnOrder.setOrderId(dto.getOrderId());
		returnOrder.setCreatorId(getCurrentUserId()); // 需要实现获取当前用户ID的方法
		returnOrder.setCreateTime(LocalDateTime.now());
		returnOrder.setStatus(0); // 草稿状态

		// 计算总金额（以服务端为准）
		BigDecimal totalAmount = BigDecimal.ZERO;

		returnOrderMapper.insert(returnOrder);

		// 创建退货单商品
		for (var itemDto : dto.getItems()) {
			PurchaseReturnOrderItem item = new PurchaseReturnOrderItem();
			item.setReturnOrderId(returnOrder.getId());
			item.setOrderItemId(itemDto.getOrderItemId());
			item.setReturnQuantity(itemDto.getReturnQuantity());
			item.setReturnPrice(itemDto.getReturnPrice());
			BigDecimal lineAmount = itemDto.getReturnPrice().multiply(new java.math.BigDecimal(itemDto.getReturnQuantity()));
			item.setReturnAmount(lineAmount);
			item.setReason(itemDto.getReason());

			returnOrderItemMapper.insert(item);
			totalAmount = totalAmount.add(lineAmount);
		}

		returnOrder.setTotalReturnAmount(totalAmount);
		returnOrder.setRemark(dto.getRemark());
		returnOrderMapper.updateById(returnOrder);

		return returnOrder.getId();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void submitForAudit(Long returnOrderId) {
		PurchaseReturnOrder returnOrder = returnOrderMapper.selectById(returnOrderId);
		if (returnOrder == null) {
			throw new RuntimeException("退货单不存在");
		}

		if (returnOrder.getStatus() != 0) {
			throw new RuntimeException("只有草稿状态的退货单才能提交审核");
		}

		// 更新状态为已提交
		returnOrder.setStatus(1);
		returnOrderMapper.updateById(returnOrder);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteReturnOrder(Long returnOrderId) {
		PurchaseReturnOrder returnOrder = returnOrderMapper.selectById(returnOrderId);
		if (returnOrder == null) {
			throw new RuntimeException("退货单不存在");
		}

		if (returnOrder.getStatus() != 0) {
			throw new RuntimeException("只有草稿状态的退货单才能删除");
		}

		// 删除商品
		returnOrderItemMapper.deleteByReturnOrderId(returnOrderId);
		// 删除主表
		returnOrderMapper.deleteById(returnOrderId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void batchDeleteReturnOrder(List<Long> returnOrderIds) {
		for (Long returnOrderId : returnOrderIds) {
			deleteReturnOrder(returnOrderId);
		}
	}

	@Override
	public IPage<PurchaseReturnOrderVO> getReturnOrderPage(Page<PurchaseReturnOrder> page, Integer status, String returnNo) {
		return returnOrderMapper.selectReturnOrderPage(page, status, returnNo);
	}

	@Override
	public PurchaseReturnOrderVO getReturnOrderDetail(Long returnOrderId) {
		// 基础信息
		PurchaseReturnOrderVO vo = returnOrderMapper.selectReturnOrderDetail(returnOrderId);
		if (vo == null) {
			return null;
		}
		// 商品明细
		List<PurchaseReturnOrderItem> items = returnOrderItemMapper.selectByReturnOrderId(returnOrderId);
		List<PurchaseReturnOrderItemVO> itemVOs = items.stream().map(it -> {
			PurchaseReturnOrderItemVO itemVO = new PurchaseReturnOrderItemVO();
			itemVO.setId(it.getId());
			itemVO.setOrderItemId(it.getOrderItemId());
			itemVO.setReturnQuantity(it.getReturnQuantity());
			itemVO.setReturnPrice(it.getReturnPrice());
			itemVO.setReturnAmount(it.getReturnAmount());
			itemVO.setReason(it.getReason());
			// 取商品名称、编码
			PurchaseOrderItem poi = purchaseOrderItemMapper.selectById(it.getOrderItemId());
			if (poi != null) {
				itemVO.setProductName(String.valueOf(poi.getProductId()));
				itemVO.setProductCode(String.valueOf(poi.getProductId()));
			}
			return itemVO;
		}).collect(Collectors.toList());
		vo.setItems(itemVOs);

		// 审核信息
		PurchaseReturnOrderAudit audit = returnOrderAuditMapper.selectByReturnOrderId(returnOrderId);
		if (audit != null) {
			PurchaseReturnOrderAuditVO auditVO = new PurchaseReturnOrderAuditVO();
			auditVO.setAuditorId(audit.getAuditorId());
			auditVO.setAuditTime(audit.getAuditTime());
			auditVO.setAuditOpinion(audit.getAuditOpinion());
			auditVO.setAuditResult(audit.getAuditResult());
			vo.setAuditInfo(auditVO);
		}

		return vo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void auditReturnOrder(Long returnOrderId, Long auditorId, String auditOpinion, Integer auditResult) {
		PurchaseReturnOrder returnOrder = returnOrderMapper.selectById(returnOrderId);
		if (returnOrder == null) {
			throw new RuntimeException("退货单不存在");
		}

		if (returnOrder.getStatus() != 1) {
			throw new RuntimeException("只有已提交状态的退货单才能审核");
		}

		// 创建审核记录
		PurchaseReturnOrderAudit audit = new PurchaseReturnOrderAudit();
		audit.setReturnOrderId(returnOrderId);
		audit.setAuditorId(auditorId);
		audit.setAuditTime(LocalDateTime.now());
		audit.setAuditOpinion(auditOpinion);
		audit.setAuditResult(auditResult);

		returnOrderAuditMapper.insert(audit);

		// 更新退货单状态
		returnOrder.setStatus(auditResult == 1 ? 2 : 3); // 2-审核通过，3-审核驳回
		returnOrderMapper.updateById(returnOrder);
	}

	@Override
	public PurchaseReturnOrderAudit getLatestAuditRecord(Long returnOrderId) {
		return returnOrderAuditMapper.selectByReturnOrderId(returnOrderId);
	}

	/**
	 * 生成退货单号
	 */
	private String generateReturnNo() {
		return "RTO" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
	}

	/**
	 * 获取当前用户ID（需要根据实际认证框架实现）
	 */
	private Long getCurrentUserId() {
		// TODO: 实现获取当前用户ID的逻辑
		return 1L;
	}
} 